<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        let input = `3
        3 5 3 4`
        let requirements = input.split('\n')
        let M = parseInt(requirements.shift())
        requirements = requirements[0].trim().split(' ').map(v => parseInt(v.trim()))
        let N = requirements.length

        let month = 0
        requirements.sort()
        let save = [...requirements]
        let res=0       
        
        let req1 = requirements.shift()
        let req2 = requirements.shift()
        
        for (let i = 1; i < 999; i++) {
            while (month < M) {
                let T = i
                if (req1 > T) {
                    req1 -= T
                } else if (req1 === T) {                    
                    req1 = requirements.length ? requirements.shift() : 0
                } else if (req1 < T) {
                    T -= req1
                    req1 = requirements.length ? requirements.shift() : 0
                    if (req2 <= T) {
                        req2 = requirements.length ? requirements.shift() : 0
                    } else {
                        req2 -= T
                    }
                }
                
                
                
                month++
            }

            if (requirements.length === 0&&req1===0&&req2===0) {                
                res=i
                i = Infinity
            } else {                
                // console.log(i,requirements);
                requirements = [...save]
                req1 = requirements.shift()
                req2 = requirements.shift()
                month=0
                
            }
        }



        console.log(res);
        console.log(requirements);

    </script>
</body>

</html>